<?php
/**
 * 阿里短信
 * Created by PhpStorm.
 * User: Yui
 * Date: 2017/5/15 0015
 * Time: 15:28
 */

namespace common\services;


use common\library\comFun;

class AliSmsSve extends BaseSve
{

    /**
     * 发送短信
     * @param $mobile //手机号码
     * @param $signName //签名
     * @param $templateCode //模板编号
     * @param $operationType //类型
     * @return array
     */
    public function send($mobile, $signName, $templateCode, $operationType)
    {
        try {
            //检查数据
            if (!comFun::checkMobile($mobile)) {
                throw new \Exception('手机号码格式错误', -1);
            }
            //检查是否已发送
            if ($this->_isSend($mobile, $operationType)) {
                return self::result('短信已发送', 0);
            }
            //创建验证码
            $code = comFun::createRandom(OC['sms_code_len'], '0123456789');
            //创建记录数据
            $data = [
                'mobile' => $mobile,
                'verify_code' => $code,
                'sign_name' => $signName,
                'template_code' => $templateCode,
                'operation_type' => $operationType,
                'create_time' => $_SERVER['REQUEST_TIME'],
            ];
            //执行发送
            $rsArr = $this->doSend($mobile, $signName, $templateCode, ['msg' => $code]);
            if ($rsArr['success']) {
                $data['status'] = 1;
            } else {
                $data['status'] = 0;
                $data['err_msg'] = $rsArr['message'];
            }
            //记录发送结果
            $SmsLogSve = new SmsLogSve();
            $rs = $SmsLogSve->add($data);

            if ($rs['code'] !== 0) {
                throw new \Exception($rs['msg'], -1);
            }
            if (!$rsArr['success']) {
                throw new \Exception('发送失败', -1);
            }
            return self::result('发送成功', 0, ['smsLifetime' => OC['sms_lifetime']]);
        } catch (\Exception $e) {
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }

    /**
     * 验证短信
     * @param $mobile
     * @param $operationType
     * @param $code
     * @return bool
     */
    public function checkVerifyCode($mobile, $operationType, $code):array
    {
        //获取验证码
        $SmsLogSve = new SmsLogSve();
        $rs = $SmsLogSve->getInfo([
            'AND',
            ['=', 'mobile', $mobile],
            ['=', 'operation_type', $operationType],//同一类型
            ['=', 'status', 1],//正常发送
            ['=', 'is_used', 0],//未使用
            ['>=', 'create_time', $_SERVER['REQUEST_TIME'] - intval(OC['sms_lifetime'])]//未过期
        ]);
        if ($rs['code'] !== 0) {
            return self::result('请获取验证码');
        }
        //判断是否正确
        $SmsLog = $rs['data']['Obj'];
        if ($SmsLog->verify_code != $code) {
            return self::result('验证码错误');
        }
        //标记已使用
        $SmsLog->is_used = 1;
        $SmsLog->use_time = $_SERVER['REQUEST_TIME'];
        $SmsLog->update();
        return self::result('验证成功', 0);
    }

    /**
     * 是否已发送
     * @param $mobile
     * @param $operationType
     * @return bool
     */
    private function _isSend($mobile, $operationType):bool
    {
        $SmsLogSve = new SmsLogSve();
        $rs = $SmsLogSve->getInfo([
            'AND',
            ['=', 'mobile', $mobile],
            ['=', 'operation_type', $operationType],//同一类型
            ['=', 'status', 1],//正常发送
            ['=', 'is_used', 0],//未使用
            ['>=', 'create_time', $_SERVER['REQUEST_TIME'] - intval(OC['sms_lifetime'])]//未过期
        ]);
        if ($rs['code'] !== 0) {
            return false;
        }
        if (empty($rs['data']['Obj'])) {
            return false;
        }
        return true;
    }


    /**
     * 发送短信
     * @param $mobile
     * @param $signName
     * @param $templateCode
     * @param $msgArr
     * @return mixed
     */
    public function doSend($mobile, $signName, $templateCode, array $msgArr):array
    {
        try {
            $host = "http://sms.market.alicloudapi.com";
            $path = "/singleSendSms";
            $method = "GET";
            $appcode = OC['sms_app_code'];
            $headers = [];
            array_push($headers, "Authorization:APPCODE " . $appcode);
            $paramString = comFun::arrToJsonStr($msgArr);
            $querys = 'ParamString=' . $paramString . '&RecNum=' . $mobile . '&SignName=' . $signName . '&TemplateCode=' . $templateCode;

            $url = $host . $path . "?" . $querys;

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, false);
            if (1 == strpos("$" . $host, "https://")) {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }

            $rs = curl_exec($curl);
            $arr = \GuzzleHttp\json_decode($rs, true);
            return $arr;
        } catch (\Exception $e) {
            return ['success' => false, 'message' => '执行发送失败'];
        }
    }
}